#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sqlite3
import os
import sys
from rich.console import Console

console = Console()

def create_trade_records_table():
    """
    创建交易记录表
    """
    try:
        # 连接到数据库（如果不存在则创建）
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 读取SQL文件内容，使用UTF-8编码
        with open('create_trade_records_table.sql', 'r', encoding='utf-8') as sql_file:
            sql_script = sql_file.read()
        
        # 执行SQL脚本
        cursor.executescript(sql_script)
        
        # 提交更改并关闭连接
        conn.commit()
        conn.close()
        
        console.print("交易记录表创建成功！", style="green")
        
    except Exception as e:
        console.print(f"创建交易记录表时出错: {e}", style="red")
        return False
    
    return True

def check_table_structure():
    """
    检查表结构是否与insert_trade_record函数匹配
    """
    try:
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 获取表结构
        cursor.execute("PRAGMA table_info(trade_records)")
        columns = cursor.fetchall()
        
        # 检查必要的列是否存在
        required_columns = ['product_name', 'direction', 'offset', 'volume', 'price', 'reason', 'timestamp']
        existing_columns = [col[1] for col in columns]
        
        missing_columns = [col for col in required_columns if col not in existing_columns]
        
        if missing_columns:
            console.print(f"警告: 表结构缺少以下列: {', '.join(missing_columns)}", style="yellow")
        else:
            console.print("表结构与insert_trade_record函数匹配！", style="green")
        
        conn.close()
        
    except Exception as e:
        console.print(f"检查表结构时出错: {e}", style="red")

if __name__ == "__main__":
    console.print("开始创建交易记录表...", style="blue")
    if create_trade_records_table():
        check_table_structure()